package com.example.pei.ithinklearnt;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.Toast;

import com.example.pei.ithinklearnt.bean.AddFriendMessage;
import com.example.pei.ithinklearnt.bean.AgreeAddFriendMessage;
import com.example.pei.ithinklearnt.bean.AddCommentMessage;
import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.db.NewComment;
import com.example.pei.ithinklearnt.db.NewFriend;
import com.example.pei.ithinklearnt.db.NewFriendManager;
import com.example.pei.ithinklearnt.db.dao.CommentDaoOrder;
import com.example.pei.ithinklearnt.db.dao.PrivateConverDaoOrder;
import com.example.pei.ithinklearnt.event.RefreshEvent;
import com.example.pei.ithinklearnt.listener.UpdateCacheListener;
import com.example.pei.ithinklearnt.model.UserModel;
import com.example.pei.ithinklearnt.utils.ToastUtil;
import com.example.pei.ithinklearnt.view.activity.Login_Activity;
import com.example.pei.ithinklearnt.view.activity.MainActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.Map;

import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMMessageType;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.newim.event.MessageEvent;
import cn.bmob.newim.event.OfflineMessageEvent;
import cn.bmob.newim.listener.BmobIMMessageHandler;
import cn.bmob.newim.notification.BmobNotificationManager;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

import static com.example.pei.ithinklearnt.utils.DialogUtil.hideSmallDeleteDialog;


public class BmobMessageHandler extends BmobIMMessageHandler {
    private Context context;

    public BmobMessageHandler(Context context) {
        this.context=context;
    }

    @Override
    public void onMessageReceive(MessageEvent messageEvent) {
        //当接受到服务器发来的消息时，次方法被调用
        executeMessage(messageEvent);
    }

    @Override
    public void onOfflineReceive(OfflineMessageEvent offlineMessageEvent) {
//每次调用connect方法时会查询一次离线消息，如果有，此方法会被调用
        Map<String, List<MessageEvent>> map = offlineMessageEvent.getEventMap();
      //  Logger.i("有" + map.size() + "个用户发来离线消息");
        //挨个检测下离线消息所属的用户的信息是否需要更新
        for (Map.Entry<String, List<MessageEvent>> entry : map.entrySet()) {
            List<MessageEvent> list = entry.getValue();
            int size = list.size();
      //      Logger.i("用户" + entry.getKey() + "发来" + size + "条消息");
            for (int i = 0; i < size; i++) {
                //处理每条消息
                executeMessage(list.get(i));
            }
        }
    }

    private void executeMessage(final MessageEvent event) {
        //检测用户信息是否需要更新
        //. 当接收到某人消息的时候，同样需要更新某人的用户信息到本地用户表中，
        // 否则在会话界面将默认显示的是用户的userId，也就是Demo中的BmobUser的objectId值。
        UserModel.getInstance().updateUserInfo(event, new UpdateCacheListener() {
            @Override
            public void done(BmobException e) {
                BmobIMMessage msg = event.getMessage();
                if (BmobIMMessageType.getMessageTypeValue(msg.getMsgType()) == 0) {
                    //自定义消息类型：0
                    processCustomMessage(msg, event.getFromUserInfo());
                } else {
                    //SDK内部内部支持的消息类型
                    processSDKMessage(msg, event);
                }
            }
        });
        //若消息里面点开了删除对话框，则应该隐藏对话框
        hideSmallDeleteDialog();
    }

    /**
     * 处理SDK支持的消息
     *
     * @param msg
     * @param event
     */
    private void processSDKMessage(BmobIMMessage msg, MessageEvent event) {

        PrivateConverDaoOrder.getInstance(context).
                updateBatchStatusUnDeleted(event.getConversation().getConversationId());

        if (BmobNotificationManager.getInstance(context).isShowNotification()) {
            //如果需要显示通知栏，SDK提供以下两种显示方式：
            Intent pendingIntent = new Intent(context, MainActivity.class);
            pendingIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);


            //TODO 消息接收：8.5、多个用户的多条消息合并成一条通知：有XX个联系人发来了XX条消息
            BmobNotificationManager.getInstance(context).showNotification(event, pendingIntent);

        } else {
            //直接发送消息事件
            EventBus.getDefault().post(event);
        }
    }

    /**
     * 处理自定义消息类型
     *
     * @param msg
     */
    private void processCustomMessage(BmobIMMessage msg, BmobIMUserInfo info) {
        //消息类型
        String type = msg.getMsgType();

        //处理消息
        if (type.equals(AddFriendMessage.ADD)) {//接收到的添加好友的请求
            NewFriend friend = AddFriendMessage.convert(msg);
            //本地好友请求表做下校验，本地没有的才允许显示通知栏--有可能离线消息会有些重复
            long id = NewFriendManager.getInstance(context).insertOrUpdateNewFriend(friend);
            if (id > 0) {
                showAddNotify(friend);
            }
        }

        else if (type.equals(AgreeAddFriendMessage.AGREE)) {//接收到的对方同意添加自己为好友,此时需要做的事情：1、添加对方为好友，2、显示通知
            AgreeAddFriendMessage agree = AgreeAddFriendMessage.convert(msg);
            addFriend(agree.getFromId());//添加消息的发送方为好友

            //这里应该也需要做下校验--来检测下是否已经同意过该好友请求，我这里省略了
            if(isFriend(agree.getUid())){
                showAgreeNotify(info, agree);
            }

        }


        else if(type.equals(AddCommentMessage.COMMENT)){
            NewComment newComment= AddCommentMessage.convert(msg);
            //往本地数据库插入一条新回复记录
            if(CommentDaoOrder.getInstance(context).insertComment(newComment)) {
                //ToastUtil.ToastShow(context,msg.getContent(),0);
            }
            //else
                //ToastUtil.ToastShow(context,"插入新回复信息失败",0);
        }

        else {
            Toast.makeText(context, "接收到的自定义消息：" + msg.getMsgType() + "," + msg.getContent() + "," + msg.getExtra(), Toast.LENGTH_SHORT).show();
        }
        //发送页面刷新的广播
        EventBus.getDefault().post(new RefreshEvent());
    }

    //查询本地是否已经是好友
    private boolean isFriend(String uid){
        List<UserInfo> friends=UserModel.getInstance().getLocalFreinds(AppApplication.getContext());
        if(friends==null||friends.size()<=0){
            return false;
        }
        for(UserInfo info:friends){
            if(info.getObjectId().equals(uid)){
                return true;
            }
        }
        return false;
    }

    /**
     * 显示对方添加自己为好友的通知
     *
     * @param friend
     */
    private void showAddNotify(NewFriend friend) {
        Intent pendingIntent = new Intent(context, Login_Activity.class);
        pendingIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        //这里可以是应用图标，也可以将聊天头像转成bitmap

        Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
        BmobNotificationManager.getInstance(context).showNotification(largeIcon,
                friend.getName(), friend.getMsg(), friend.getName() + "请求添加你为朋友", pendingIntent);
    }

    /**
     * 显示对方同意添加自己为好友的通知
     *
     * @param info
     * @param agree
     */
    private void showAgreeNotify(BmobIMUserInfo info, AgreeAddFriendMessage agree) {
        Intent pendingIntent = new Intent(context, Login_Activity.class);
        pendingIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
        BmobNotificationManager.getInstance(context).showNotification(largeIcon, info.getName(), agree.getMsg(), agree.getMsg(), pendingIntent);
    }

    /**
     * TODO 好友管理：9.11、收到同意添加好友后添加好友
     *
     * @param uid
     */
    private void addFriend(String uid) {
        UserInfo user = new UserInfo();
        user.setObjectId(uid);
        UserModel.getInstance()
                .agreeAddFriend(user, new SaveListener<String>() {
                    @Override
                    public void done(String s, BmobException e) {
                        if (e == null) {

                        } else {

                        }
                    }
                });
    }


}
